import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";
import { wrapperEnv } from "./build/utils";
import { createProxy } from "./build/vite/proxy";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { createHtmlPlugin } from "vite-plugin-html";
import { viteVConsole } from "vite-plugin-vconsole";
import { resolve } from "path";
import legacy from "@vitejs/plugin-legacy";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env);
  // console.log("viteEnv:", viteEnv);
  const {
    VITE_PROXY,
    VITE_GLOB_APP_TITLE,
    VITE_DROP_CONSOLE,
    VITE_OPEN_VCONSOLE,
    VITE_PORT,
  } = viteEnv;

  return {
    plugins: [
      vue(),
      // vueDevTools(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹(路径为存放所有svg图标的文件夹不单个svg图标)
        iconDirs: [resolve(process.cwd(), "src/assets/svg")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
      legacy({
        targets: ['defaults', 'not IE 11', 'Chrome >= 53'], // 指定支持 Chrome 53 及以上
        additionalLegacyPolyfills: ['core-js/stable', 'regenerator-runtime/runtime'], // 添加额外的 polyfill
        renderLegacyChunks: true,
        modernPolyfills: true, // 为现代浏览器生成 polyfills
      }),
      createHtmlPlugin({
        inject: {
          data: {
            //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
            title: VITE_GLOB_APP_TITLE,
          },
        },
      }),
      viteVConsole({
        entry: [resolve("src/main.js")], // or you can use entry: [path.resolve('src/main.ts')]
        localEnabled: VITE_OPEN_VCONSOLE,
        enabled: VITE_OPEN_VCONSOLE,
        config: {
          maxLogNumber: 1000,
          theme: "light", // light | dark
        },
      }),
    ],
    resolve: {
      // ↓路径别名
      alias: {
        "@": resolve(__dirname, "./src"),
      },
    },
    esbuild: {
      drop: VITE_DROP_CONSOLE ? ["console", "debugger"] : [],
    },
    server: {
      // Listening on all local IPs
      host: true,
      https: false,
      port: VITE_PORT,
      proxy: createProxy(VITE_PROXY),
    },
    build: {
      // target: "es2015", // 设置构建目标为 ES2015 或更高版本
      sourcemap: false, // 打包后是否生成 source map 文件
    },
  };
});
